package com.baitiaojun.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baitiaojun.api.domain.user.UserCoin;
import com.baitiaojun.api.exception.ConditionException;
import com.baitiaojun.api.util.ConstantUtil;
import com.baitiaojun.user.mapper.UserCoinMapper;
import com.baitiaojun.user.service.UserCoinService;
import com.baitiaojun.user.support.RedisSupport;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @类名 UserCoinServiceImpl
 * @描述 TODO
 * @作者 白条君
 * @创建日期 2023/2/23 16:12
 * @版本 1.0
 */
@Service
public class UserCoinServiceImpl implements UserCoinService {

    @Resource
    private UserCoinMapper userCoinMapper;

    @Resource
    private RedisSupport redisSupport;

    @Override
    public Integer getUserCoin(Long userId, String token) {
        Object value = redisSupport.getHash(token, ConstantUtil.USER_COINS);
        if(ObjectUtils.isEmpty(value)) {
            Integer userCoins = userCoinMapper.selectAmountByUserId(userId);
            redisSupport.setHash(token, ConstantUtil.USER_COINS, userCoins);
            return userCoins;
        }
        return JSONObject.parseObject(JSONObject.toJSONString(value), Integer.class);
    }

    @Override
    public void updateUserCoin(UserCoin userCoin, String token) throws ConditionException {
        int res = userCoinMapper.updateUserCoinByUserId(userCoin);
        if(res == 0) {
            throw new ConditionException("更新用户硬币数量失败");
        }
        redisSupport.setHash(token, ConstantUtil.USER_COINS, userCoin.getAmount());
    }
}
